﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace DB
{
    public class EmailInfo
    {
        public string Email;
        public string Name;
        public string Domain;
        public int DeliveryStatus;
    }
    public class EmailsDb : DbBase
    {
        private EmailsDb(DbEngineBase dbEngineBase)
            : base(dbEngineBase)
        {
        }

        private static EmailsDb _dbMysql;
        public static EmailsDb DbMysql
        {
            get 
            {
                return _dbMysql ?? (_dbMysql = new EmailsDb(new DbEngineMysql("Server=mail.maibey.com;userid=love;password=1234567;Database=Barn;CharSet=utf8;")));
            }
        }

        public List<EmailInfo> GetEmailsList(string strTableName)
        {
            var strErr = "";
            var dt = this.QueryData("Select Email,Name,Domain,DeliveryStatus from " + strTableName + " where DeliveryStatus = 0", ref strErr);
            return Get(dt);
        }
        public bool UpdateEmailDeliveryStatus(string email, string strTableName)
        {
            var strErr = "";
            var strSql = "Update " + strTableName + " set "
                         + "DeliveryStatus = 1"
                         + " WHERE email = '" + email + "'";
            return this.Exec(strSql, ref strErr);
        }
        private List<EmailInfo> Get(DataTable dt)
        {
            var listRtn = new List<EmailInfo>();
            listRtn = ListCreater<EmailInfo>.CreateFromDataTable(dt);
            return listRtn;
        }


        public bool UpdateMailChimpEmailStatus(string email, string status)
        {
            var strErr = "";
            var strSql = "Update Alllovebling_Email_Status set "
                         + " LastSender = '" + status
                         + "' WHERE email = '" + email + "'";
            return this.Exec(strSql, ref strErr);
        }

        public List<EmailInfo> GetMailChimpEmailList(int iCount)
        {
            var strErr = "";
            var dt = this.QueryData("Select Email,Name,Domain from Alllovebling_Email_Status where LastSender = '' and LastSent < ADDDATE(NOW(),-15) order by LastSent LIMIT 0, " + iCount, ref strErr);
            return Get(dt);
        }

        public void UpdateMailChimpEmailLastSent(List<EmailInfo> list)
        {
            foreach (var emailInfo in list)
            {
                var strErr = "";
                var strSql = "Update Alllovebling_Email_Status set LastSent = NOW() where email = '" + emailInfo.Email + "'";
                this.Exec(strSql, ref strErr);
            }
        }
    }
}
